#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// #include <arpa/inet.h>
#include <unistd.h>
#include <stdint.h>cc
// #include <sys/socket.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib") // 链接 ws2_32.lib 库

#define PORT 12345
#define BUFFER_SIZE 1024

// 定义协议数据结构
typedef struct
{
    uint16_t frameHeader;     // 帧头 (2字节)
    uint8_t frameType;        // 帧类型 (1字节)
    uint16_t dataFrameLength; // 数据帧长度 (2字节)
    uint64_t deviceSN;        // 采集设备编号 (8字节)
    uint64_t timestamp;       // 时间戳 (8字节)
    uint8_t dataItemCount;    // 数据项数量 (1字节)
    uint8_t *dataItems;       // 数据项内容 (N * 10字节)
    uint8_t rollingCheck;     // 滚动校验 (1字节)
    uint8_t checksum;         // 累加校验 (1字节)
} ProtocolPacket;

// 解析协议数据包
int parsePacket(uint8_t *buffer, size_t buffer_len, ProtocolPacket *packet)
{
    if (buffer_len < 22)
    {              // 至少需要22字节（2 + 1 + 2 + 8 + 8 + 1）
        return -1; // 数据包不完整
    }

    // 解析帧头
    packet->frameHeader = (buffer[1] << 8) | buffer[0];

    // 解析帧类型
    packet->frameType = buffer[2];

    // 解析数据帧长度
    packet->dataFrameLength = (buffer[4] << 8) | buffer[3];

    // 解析采集设备编号
    packet->deviceSN = 0;
    for (int i = 0; i < 8; i++)
    {
        packet->deviceSN |= (uint64_t)buffer[5 + i] << (8 * i);
    }

    // 解析时间戳
    packet->timestamp = 0;
    for (int i = 0; i < 8; i++)
    {
        packet->timestamp |= (uint64_t)buffer[13 + i] << (8 * i);
    }

    // 解析数据项数量
    packet->dataItemCount = buffer[21];

    // 检查数据长度是否匹配
    size_t expected_len = 22 + packet->dataItemCount * 10; // 假设每个数据项10字节
    if (buffer_len < expected_len)
    {
        return -1; // 数据包不完整
    }

    // 分配内存并复制数据项内容
    packet->dataItems = (uint8_t *)malloc(packet->dataItemCount * 10);
    if (packet->dataItems == NULL)
    {
        return -1; // 内存分配失败
    }
    memcpy(packet->dataItems, &buffer[22], packet->dataItemCount * 10);

    // 解析滚动校验
    packet->rollingCheck = buffer[22 + packet->dataItemCount * 10];

    // 解析累加校验
    packet->checksum = buffer[23 + packet->dataItemCount * 10];

    return 0; // 解析成功
}

// 打印协议数据包
void printPacket(ProtocolPacket *packet)
{
    printf("Frame Header: 0x%04X\n", packet->frameHeader);
    printf("Frame Type: 0x%02X\n", packet->frameType);
    printf("Data Frame Length: %d\n", packet->dataFrameLength);
    printf("Device SN: %lu\n", packet->deviceSN);
    printf("Timestamp: %lu\n", packet->timestamp);
    printf("Data Item Count: %d\n", packet->dataItemCount);
    for (int i = 0; i < packet->dataItemCount; i++)
    {
        printf("Data Item %d: ", i + 1);
        for (int j = 0; j < 10; j++)
        {
            printf("%02X ", packet->dataItems[i * 10 + j]);
        }
        printf("\n");
    }
    printf("Rolling Check: 0x%02X\n", packet->rollingCheck);
    printf("Checksum: 0x%02X\n", packet->checksum);
}

// 服务端主函数
int main()
{
    printf("server Program started\n");
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    // socklen_t client_len = sizeof(client_addr);
    int client_len = sizeof(client_addr);
    uint8_t buffer[BUFFER_SIZE];
    size_t bytes_received;
    printf("创建 socket\n");
    // 创建 socket
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    // 绑定 socket
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
    {
        perror("Bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听连接
    if (listen(server_fd, 5) == -1)
    {
        perror("Listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    printf("Server listening on port %d...\n", PORT);

    // 接受客户端连接
    if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_len)) == -1)
    {
        perror("Accept failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 接收数据
    bytes_received = recv(client_fd, buffer, BUFFER_SIZE, 0);
    if (bytes_received == -1)
    {
        perror("Receive failed");
        close(client_fd);
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 解析数据包
    ProtocolPacket packet;
    if (parsePacket(buffer, bytes_received, &packet) == 0)
    {
        printPacket(&packet);
    }
    else
    {
        printf("Failed to parse packet.\n");
    }

    // 释放内存
    free(packet.dataItems);

    // 关闭连接
    close(client_fd);
    close(server_fd);

    return 0;
}